package com.cxs.security;

import cn.hutool.json.JSONUtil;
import com.cxs.common.lang.Const;
import com.cxs.common.result.ResultVO;
import com.cxs.utils.JwtUtil;
import com.cxs.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功的处理，实现AuthenticationSuccessHandler
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应类型为 JSON 格式的字符串，如果不加这句话，那么浏览器显示的将是乱码
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        // 生成JWT
        // authentication.getName(): 用户名
        String jwt = jwtUtil.generateToken(authentication.getName());
        // jwtUtil.getHeader(): 从配置文件获取自定义的header，值为authorization
        // 把jwt写入客户端响应体的header中，客户端通过res.headers['authorization']获取JWT，存入缓存
        response.setHeader(jwtUtil.getHeader(), jwt);

        ResultVO resultVO = new ResultVO<>("00000");
        // 向客户端浏览器输出数据
        outputStream.write(JSONUtil.toJsonStr(resultVO).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
